package com.example.gustavo.hello.listener;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

/**
 * 随着RecyclerView滚动,显示/隐藏header
 * Created by gustavo on 2015/3/9.
 */
public abstract class OnScrollHideHeaderListener extends RecyclerView.OnScrollListener {
    private int distanceY;
    private boolean isShowing = true;
    private int distance = 40;

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        //避免统计错误数据
        if((dy > 0 && isShowing) || (dy < 0 && !isShowing)){

            distanceY += dy;
        }



        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();

        if(firstVisibleItemPosition == 0){

            if(!isShowing){
                onShow();
                isShowing = true;
            }

        }else{

            if(distanceY > distance && isShowing){
                distanceY = 0;
                isShowing = false;

                onHide();

            }else if(distanceY < -distance && !isShowing){

                distanceY = 0;
                isShowing = true;

                onShow();
            }
        }

    }

    /**
     * 显示header
     */
    public abstract void onShow();

    /**
     * 隐藏header
     */
    public abstract void onHide();
}
